;;; init-packages.el --- Emacs packages configure -*- lexical-binding: t -*-
;;; Commentary:
;;; Code:

(eval-when-compile
  (require 'cl-macs))
(require 'seq)
(require 'package)

;; (setq package-archives '(("gnu"    . "https://elpa.gnu.org/packages/")
;;                          ("nongnu" . "https://elpa.nongnu.org/nongnu/")
;;                          ("melpa"  . "https://melpa.org/packages/")))

(setq package-archives '(("gnu"    . "http://mirrors.tuna.tsinghua.edu.cn/elpa/gnu/")
                         ("nongnu" . "http://mirrors.tuna.tsinghua.edu.cn/elpa/nongnu/")
                         ("melpa"  . "http://mirrors.tuna.tsinghua.edu.cn/elpa/melpa/")))

(defconst ctrlwei/elpa-packages
  '(;; minibuffer and completion
    vertico
    orderless
    marginalia
    consult
    consult-dir
    consult-lsp
    corfu
    cape
    embark
    embark-consult
    evil
    ;;
    ;; eaf
    epc
    ctable
    deferred
    ;;
    ace-window
    avy
    darkroom
    dap-mode
    docker
    elfeed
    expand-region
    flycheck
    flycheck-pycheckers
    format-all
    git-timemachine
    go-mode
    htmlize
    helpful
    ibuffer-vc
    imenu-list
    jdecomp
    langtool
    langtool-popup
    lsp-mode
    lsp-java
    lsp-pyright
    lsp-treemacs
    lsp-ui
    lua-mode
    magit
    markdown-mode
    mwim
    org-contrib
    paredit
    pdf-tools
    pdf-view-restore
    posframe
    pyim
    rg
    rime
    rust-mode
    symbol-overlay
    treemacs
    vc-msg
    yaml-mode
    yasnippet
    yasnippet-snippets
    undo-fu-session
    valign
    vterm
    vterm-toggle
    wgrep
    winum
    nov
    xr)
  "Packages from elpa for personal use.")

;; package.el updates the saved version of package-selected-packages correctly only
;; after custom-file has been loaded, which is a bug. Purcell work around this by adding
;; the required packages to package-selected-packages after startup is complete.
;; but, I dont like the startup message "Wrote /root/.emacs.d/custom.el [2 times]"

(defvar ctrlwei/needs-reset-selected-packages nil
  "If no-nil, Emacs needs reset value of package-selected-packages in `custom-file'.")

(defun packages-installed-p ()
  "Return t if there has some packages not installed yet."
  (cl-loop for pkg in ctrlwei/elpa-packages
        when (not (package-installed-p pkg)) do (cl-return nil)
        finally (cl-return t)))

(unless (packages-installed-p)
  (setq ctrlwei/needs-reset-selected-packages t)
  (message "Refreshing package database...")
  (package-refresh-contents)
  (dolist (pkg ctrlwei/elpa-packages)
    (unless (package-installed-p pkg)
      (package-install pkg))))

(if ctrlwei/needs-reset-selected-packages
    (add-hook 'after-init-hook
              (lambda () (package--save-selected-packages
                          (seq-uniq (append ctrlwei/elpa-packages package-selected-packages))))))

(provide 'init-packages)
;;; init-packages.el ends here
